// import { getEnabledCategories } from "trace_events";

;(function($){
/**
 * 变量区
 * 
 * @var   loadedData  观察者模式 数据加载的观察者;
 * 
 */
    var loadedData = $.Callbacks();
    var addCart = $.Callbacks();
    var reduceCart = $.Callbacks();
    var choiceShop = $.Callbacks();
    var showCharts = $.Callbacks();
    var cartsList = $.Callbacks();
    var cartsListAdd = $.Callbacks();
    var cartsListReduce = $.Callbacks();

/**
 *  数据仓库;
 *    
 *    pxxList ： ajax加载过来 pxx数据; {key:object}
 */

    var GLOBAL_STORE = {
        productList : {},
        carts : getCarts(),
        shopAttr : ""
    }
/**
 *  函数区
 *  
 *   @function renderBtn 渲染btn;
 *   @function init 初始化页面;
 * 
 */
    // 增加购物车数量
    function addCartsData(){
        var optEle = $(this).parent();
        console.log(optEle.prevAll(".price")[0].children[1].innerHTML);
        var id = optEle.attr("data-id");
        var carts = null;

        if(!(GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr] instanceof Array)){
            GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr] = [];
        }

        var hasSameGoods = GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr].some(item=>{
            if(item.id == id){
                item.count ++;
                return true;
            }
        })
        if(!hasSameGoods){
            GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr].push({
                id : id,
                count : 1,
                price : parseFloat(optEle.prevAll(".price")[0].children[1].innerHTML)
            });
        }
        console.log(GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr]);
        saveData("carts", GLOBAL_STORE.carts)
    }
    // 删除购物车数据
    function reduceCartsData(){
        var optEle = $(this).parent();
        

    }
    // 保存数据
    function saveData(type, json){
        localStorage.setItem(type, JSON.stringify(json));
    }
    // 初始化购物车
    function getCarts(){
        if(localStorage.getItem("carts")){
            return JSON.parse(localStorage.getItem("carts"));
        }else{
            return {};
        }
    }
    // 渲染购物车
    function renderCarts(){
        // 1.查找购物车数量
        var cartsList = GLOBAL_STORE.carts[GLOBAL_STORE.shopAttr];
        cartsList = cartsList ? cartsList : [];
        console.log(cartsList);
        var total = 0;
        cartsList.forEach((item,index) => {
            if(index !== 0){
                total += item.count;
            }
        })
        $(".count .allCount").html(total);
    }
    function init(){
        bindEvent();
    }
   
    function bindEvent(){
        loadedData.add([renderCarts]);
        addCart.add([addCartsData,renderCarts]);

        $(".productinfo_main").on("click", ".add", addCart.fire);
    }
$(init);

})(jQuery)